<template>
  <div class="app">
    <!-- 侧边栏导航 -->
    <el-drawer :visible.sync="isSidebarOpen" direction="ltr" size="250px" title="菜单">
      <el-menu 
        default-active="1" 
        @select="handleSelect"
        active-text-color="#409EFF">
        <el-menu-item index="1">
          <i class="el-icon-monitor"></i>
          <span>检测界面</span>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-document"></i>
          <span>历史记录</span>
        </el-menu-item>
        <el-menu-item index="3">
          <i class="el-icon-user"></i>
          <span>个人管理</span>
        </el-menu-item>
        <el-menu-item index="4">
          <i class="el-icon-setting"></i>
          <span>检测配置</span>
        </el-menu-item>
      </el-menu>
    </el-drawer>

    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="left-section">
        <el-button 
          @click="isSidebarOpen = true" 
          icon="el-icon-menu" 
          circle
          class="menu-button"></el-button>
        <h1 class="system-title">细胞检测系统</h1>
      </div>
      <div class="right-section">
        <el-dropdown trigger="click">
          <span class="user-info">
            <el-avatar :size="36" :src="user.avatar"></el-avatar>
            <span class="user-name">{{ user.name }}</span>
            <i class="el-icon-arrow-down"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="activePage = 'personal'">
              <i class="el-icon-user"></i>个人中心
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="logout">
              <i class="el-icon-switch-button"></i>退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <el-main class="main-content">
      <!-- 检测界面 -->
      <div v-if="activePage === 'detection'" class="container">
        <div class="left-panel">
          <h3 class="panel-title">上传细胞图片</h3>
          <el-upload 
            class="upload-container"
            action="#" 
            list-type="picture-card" 
            :multiple="true" 
            :limit="100" 
            :file-list="uploadedFiles"
            :before-upload="beforeUpload" 
            :on-preview="handlePreview" 
            :on-remove="handleRemove"
            :http-request="handleUpload">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="upload-tip">
              支持扩展名：.jpg/.png，单张不超过5MB
            </div>
          </el-upload>
          <el-button 
            type="primary" 
            class="detect-button"
            @click="handleDetection"
            :disabled="uploadedFiles.length === 0"
            :loading="isDetecting">
            {{ isDetecting ? '检测中...' : '开始检测' }}
          </el-button>
        </div>

        <div class="right-panel">
          <h3 class="panel-title">检测结果（共 {{ processedImages.length }} 张）</h3>
          <div class="result-container">
            <div v-if="processedImages.length > 0" class="result-display">
              <div class="image-container">
                <img 
                  :src="processedImages[currentProcessedIndex].url" 
                  class="result-image"
                  @click="handlePreview({ url: processedImages[currentProcessedIndex].url })">
                <div class="image-nav">
                  <el-button 
                    class="nav-button prev" 
                    @click="prevProcessedImage" 
                    :disabled="currentProcessedIndex === 0">
                    <i class="el-icon-arrow-left"></i>
                  </el-button>
                  <el-button 
                    class="nav-button next" 
                    @click="nextProcessedImage"
                    :disabled="currentProcessedIndex === processedImages.length - 1">
                    <i class="el-icon-arrow-right"></i>
                  </el-button>
                </div>
                <div class="image-info">
                  {{ currentProcessedIndex + 1 }} / {{ processedImages.length }} - 
                  {{ processedImages[currentProcessedIndex].name }}
                </div>
              </div>
              
              <div class="stats-container">
                <h4>检测统计结果</h4>
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="红细胞(RBC)">{{ currentStats.RBC }}</el-descriptions-item>
                  <el-descriptions-item label="白细胞(WBC)">{{ currentStats.WBC }}</el-descriptions-item>
                  <el-descriptions-item label="血小板(PLT)">{{ currentStats.Platelets }}</el-descriptions-item>
                  <el-descriptions-item label="检测时间">{{ currentStats.date }}</el-descriptions-item>
                  <el-descriptions-item label="可信度" :span="2">{{ currentStats.confidence }}</el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
            
            <div v-else class="empty-result">
              <el-empty :description="uploadedFiles.length > 0 ? '等待检测结果...' : '请上传待检测图片'"></el-empty>
            </div>
          </div>
        </div>
      </div>

      <!-- 历史记录 -->
      <div v-if="activePage === 'history'" class="history-container">
        <history-logs ref="historyLogs"/>
      </div>

      <!-- 个人管理 -->
      <div v-if="activePage === 'personal'" class="personal-container">
        <personal-management ref="personalManager"/>
      </div>

      <!-- 检测配置 -->
      <div v-if="activePage === 'config'" class="config-container">
        <detection-config ref="detectionConfig"/>
      </div>

      <!-- 图片预览对话框 -->
      <el-dialog 
        :visible.sync="previewVisible" 
        title="图片预览" 
        width="75%"
        top="5vh">
        <img :src="previewImage" class="preview-image">
      </el-dialog>
    </el-main>
  </div>
</template>

<script>
import HistoryLogs from '../components/HistoryLogs.vue';
import PersonalManagement from '../components/PersonalManagement.vue';
import DetectionConfig from '../components/DetectionConfig.vue';
import instance from '../axios/index.js';

export default {
  name: 'App',
  components: {
    HistoryLogs,
    PersonalManagement,
    DetectionConfig
  },
  data() {
    return {
      isSidebarOpen: false,
      activePage: 'detection',
      isDetecting: false,
      previewVisible: false,
      previewImage: '',
      currentProcessedIndex: 0,
      user: {
        name: '张医生',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      },
      uploadedFiles: [],
      processedImages: [],
      currentStats: {
        RBC: '--',
        WBC: '--',
        Platelets: '--',
        confidence: '--',
        date: '--'
      }
    };
  },
  methods: {
    handleSelect(index) {
      this.activePage = index === "1" ? "detection" : 
                       index === "2" ? "history" : 
                       index === "3" ? "personal" : 
                       "config";
      this.isSidebarOpen = false;
    },
    
    beforeUpload(file) {
      const isImage = ['image/jpeg', 'image/png'].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!');
        return false;
      }
      return isImage && isLt5M;
    },
    
    handlePreview(file) {
      this.previewImage = file.url;
      this.previewVisible = true;
    },
    
    handleRemove(file, fileList) {
      this.uploadedFiles = fileList;
    },
    
    handleUpload({ file }) {
      this.uploadedFiles.push({
        name: file.name,
        url: URL.createObjectURL(file),
        raw: file
      });
    },
    
    async handleDetection() {
      if (this.uploadedFiles.length === 0) {
        this.$message.warning('请先上传图片');
        return;
      }
      
      this.isDetecting = true;
      try {
        const formData = new FormData();
        this.uploadedFiles.forEach(file => {
          formData.append('images', file.raw);
        });
        
        const response = await instance.post('/api/detect/detect', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        
        if (response.data.success) {
          this.processedImages = response.data.data.map(item => ({
            name: item.filename,
            url: item.image,
            stats: {
              RBC: item.rbc,
              WBC: item.wbc,
              Platelets: item.platelets,
              confidence: item.confidence,
              date: new Date().toLocaleString()
            }
          }));
          this.currentProcessedIndex = 0;
          this.updateCurrentStats();
          this.$message.success('检测完成');
        } else {
          this.$message.error(response.data.message || '检测失败');
        }
      } catch (error) {
        console.error('检测出错:', error);
        this.$message.error('检测过程中出错');
      } finally {
        this.isDetecting = false;
      }
    },
    
    prevProcessedImage() {
      if (this.currentProcessedIndex > 0) {
        this.currentProcessedIndex--;
        this.updateCurrentStats();
      }
    },
    
    nextProcessedImage() {
      if (this.currentProcessedIndex < this.processedImages.length - 1) {
        this.currentProcessedIndex++;
        this.updateCurrentStats();
      }
    },
    
    updateCurrentStats() {
      if (this.processedImages.length > 0) {
        this.currentStats = { ...this.processedImages[this.currentProcessedIndex].stats };
      }
    },
    
    logout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中这里调用退出接口
        this.$message.success('已退出登录');
        // 跳转到登录页
      });
    }
  }
};
</script>

<style scoped lang="less">
.app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 60px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    
    .left-section {
      display: flex;
      align-items: center;
      
      .menu-button {
        margin-right: 15px;
      }
      
      .system-title {
        margin: 0;
        font-size: 18px;
        color: #333;
      }
    }
    
    .right-section {
      .user-info {
        display: flex;
        align-items: center;
        cursor: pointer;
        
        .user-name {
          margin: 0 8px 0 12px;
          font-size: 14px;
        }
      }
    }
  }

  .main-content {
    flex: 1;
    padding: 20px;
    overflow: auto;
    
    .container {
      display: flex;
      height: calc(100vh - 100px);
      gap: 20px;
      
      .left-panel, .right-panel {
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
        padding: 20px;
      }
      
      .left-panel {
        width: 380px;
        flex-shrink: 0;
        
        .panel-title {
          margin-top: 0;
          margin-bottom: 20px;
          color: #333;
        }
        
        .upload-container {
          /deep/ .el-upload-list--picture-card .el-upload-list__item {
            width: 100px;
            height: 100px;
          }
          
          /deep/ .el-upload--picture-card {
            width: 100px;
            height: 100px;
            line-height: 100px;
          }
        }
        
        .upload-tip {
          color: #909399;
          font-size: 12px;
          margin: 10px 0;
        }
        
        .detect-button {
          width: 100%;
          margin-top: 15px;
        }
      }
      
      .right-panel {
        flex: 1;
        
        .panel-title {
          margin-top: 0;
          margin-bottom: 20px;
          color: #333;
        }
        
        .result-container {
          height: calc(100% - 40px);
          
          .result-display {
            display: flex;
            height: 100%;
            gap: 20px;
            
            .image-container {
              flex: 1;
              position: relative;
              background-color: #f5f5f5;
              border-radius: 4px;
              display: flex;
              justify-content: center;
              align-items: center;
              
              .result-image {
                max-width: 100%;
                max-height: 100%;
                cursor: pointer;
              }
              
              .image-nav {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                width: 100%;
                display: flex;
                justify-content: space-between;
                padding: 0 10px;
                
                .nav-button {
                  padding: 12px;
                  font-size: 16px;
                  background-color: rgba(255, 255, 255, 0.8);
                  
                  &:hover:not(:disabled) {
                    background-color: #fff;
                  }
                }
              }
              
              .image-info {
                position: absolute;
                bottom: 10px;
                left: 50%;
                transform: translateX(-50%);
                background-color: rgba(255, 255, 255, 0.8);
                padding: 5px 15px;
                border-radius: 15px;
                font-size: 14px;
                color: #606266;
              }
            }
            
            .stats-container {
              width: 300px;
              flex-shrink: 0;
              
              h4 {
                margin-top: 0;
                margin-bottom: 15px;
              }
            }
          }
          
          .empty-result {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
    
    .history-container, 
    .personal-container,
    .config-container {
      height: calc(100vh - 100px);
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
      padding: 20px;
    }
    
    .preview-image {
      width: 100%;
      display: block;
      margin: 0 auto;
    }
  }
}
</style>